package com.kis.core.scan;

import com.kis.core.util.enums.ConstEnum;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.remoting.caucho.HessianServiceExporter;

import java.util.Map;

/**
 * Created by wongloong on 16-5-4.
 */
public class AutoScanServerBean implements ApplicationContextAware, BeanDefinitionRegistryPostProcessor, InitializingBean, BeanNameAware {
    private String basePackage;
    private String beanName;
    private ApplicationContext applicationContext;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        BeanDefinitionBuilder hessianBean = BeanDefinitionBuilder.rootBeanDefinition(HessianServiceExporter.class);
        Scan scan = new Scan(basePackage, applicationContext, ConstEnum.SERVER);
        Map<String, BeanDefinitionBuilder> beans = scan.doScan();
        for (Map.Entry entity : beans.entrySet()) {
            if (!applicationContext.containsBean(entity.getKey().toString())) {
                beanDefinitionRegistry.registerBeanDefinition(entity.getKey().toString(), ((BeanDefinitionBuilder) entity.getValue()).getBeanDefinition());
            }
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
    }

    @Override
    public void setBeanName(String s) {
        this.beanName = s;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
    }

    public String getBasePackage() {
        return basePackage;
    }

    public void setBasePackage(String basePackage) {
        this.basePackage = basePackage;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
